<template>
  <div class="vue-box" style="display: none;" :style="'display: block;'">


    <!-- ------- 内容部分 ------- -->
    <div class="s-body">
      <div class="c-panel">
        <div class="c-title">{{ title }}</div>
        <el-form v-if="m">
          <div class="c-item br">
            <label class="c-label">标题：
            </label>
            <el-input v-model="m.title" style="width: 800px;" placeholder="例如：2002年的第一场雪"></el-input>
          </div>
          <div class="c-item br editor-item">
            <label class="c-label">内容：</label>
            <div class="editor-box">
              <div id="toolbar-container"></div>
              <div id="editor-container"></div>
            </div>
            <div style="clear: both;"></div>
          </div>
          <div class="c-item br s-ok">
            <el-button @click="peek()">预览</el-button>
            <el-button type="warning" @click="draft()">保存为草稿</el-button>
            <el-button type="primary" @click="ok()">保存并发布</el-button>
          </div>
          <div style="margin-top: 10px;"></div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
let editor = undefined
let PATH = "/notice"
module.exports = {
  components: {},
  watch: {},
  data() {
    return {
      title: '发布公告',
      m: {},		// 实体对象
    }
  },
  methods: {
    createEditor: function (content) {
      let token = localStorage.getItem('token')
      let t = JSON.parse(token)
      let handData = {}
      handData[t.tokenName] = t.tokenValue
      let E = window.wangEditor

      const editorConfig = {MENU_CONF: {}}
      editorConfig.placeholder = '请输入公告内容'
      editorConfig.MENU_CONF['uploadImage'] = {
        server: sa.cfg.api_url + PATH + '/upload-image',

        timeout: 10 * 1000, // 5s

        fieldName: 'file',
        meta: {token: 'xxx', a: 100},
        metaWithUrl: true, // join params to url
        headers: handData,

        maxFileSize: 10 * 1024 * 1024, // 10M

        base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

        onBeforeUpload(file) {
          console.log('onBeforeUpload', file)

          return file // will upload this file
          // return false // prevent upload
        },
        // 自定义插入图片
        customInsert(res, insertFn) {  // TS 语法
          // customInsert(res, insertFn) {                  // JS 语法
          // res 即服务端的返回结果
          // 从 res 中找到 url alt href ，然后插入图片
          insertFn(sa.getImgPath(res.data.url), res.data.alt, '')
        },
        onProgress(progress) {
          console.log('onProgress', progress)
        },
        onSuccess(file, res) {
          console.log('onSuccess', file, res)
        },
        onFailed(file, res) {
          alert(res.message)
          console.log('onFailed', file, res)
        },
        onError(file, err, res) {
          alert(err.message)
          console.error('onError', file, err, res)
        },
      }

      editorConfig.onChange = (editor) => {
        this.m.content = editor.getHtml();
      }
      editor = E.createEditor({
        html: content,
        selector: '#editor-container',
        config: editorConfig,
        mode: 'default' // 或 'simple' 参考下文
      })

      // 创建工具栏
      let toolbar = E.createToolbar({
        editor,
        selector: '#toolbar-container',
        mode: 'default' // 或 'simple' 参考下文
      })
      toolbar.getConfig().excludeKeys = [
        'group-video',
        'fullScreen',
        'insertTable',
      ]
    },
    init: function () {
      this.m = this.createModel();
      this.createEditor(this.m.content);
    },
    f5: function () {
      let noticeId = sa.getItem('notice-id');
      this.$nextTick(() => {
        if (noticeId) {
          this.title = '修改公告'
          sa.ajax(PATH + '/get', {id: noticeId}, (res) => {
            this.m = res.data
            console.log(this.m)
            editor.setHtml(this.m.content)
            sa.removeItem('notice-id')
          }, {type: 'get'})
        }
      })
    },
    // 创建一个 默认Model
    createModel: function () {
      return {
        title: '默认标题',
        content: '<h1 style="text-align: center;">你好世界</h1><p>这是公告内容</p>',
      }
    },
    peek: function () {
      sa.checkNull(this.m.title, '请输入公告标题');
      layer.open({
        title: this.m.title,
        type: 1,
        content: this.m.content,//这里content是一个普通的String
        shadeClose: true,	// 是否点击遮罩关闭
        maxmin: true, // 显示最大化按钮
        shade: 0.8,		// 遮罩透明度
        scrollbar: false,	// 屏蔽掉外层的滚动条
        moveOut: true,		// 是否可拖动到外面
        area: ['60%', '80%'],	// 大小
      });
    },
    draft: function () {
      sa.alert('确定保存为草稿？', () => {
        this.m.type = 'todo'
        this.save()
      })
    },
    save: function () {
      // 验证
      sa.checkNull(this.m.title, '请输入公告标题');
      sa.ajax(PATH + "/save-or-update", this.m, (res) => {
        sa.alert(res.msg, () => {
        })
      }, {})
    },
    // 提交数据
    ok: function () {
      sa.alert('确认发布？', () => {
        this.m.type = 'release'
        this.save()
      })
    },
  },
  mounted() {
    this.init();
  },
  created() {
    this.f5()
  }
}
</script>

<style scoped>
/* wang富文本编辑器 */
.editor-item {
  width: 100%;
  height: auto;
}

.editor-item .c-label {
  float: left;
}

.editor-item .editor-box {
  float: left;
  width: 80%;
  margin-top: 0px;
  margin-left: 0px;
}

.editor-item #editor-container .w-e-scroll {
  height: 300px;
  background-color: #FFF;
}

.editor-item #toolbar-container {
  padding-top: 5px !important;
}

.editor-item .w-e-text-placeholder {
  top: 10px;
}

/* 尽量小点 */
.editor-item .editor-box {
  float: left;
  width: 800px;
}

.editor-item .editor-box img {
  max-width: 200px !important;
}
</style>
